<template>
  <div class="toLogin">
    <el-form
      ref="loginRef"
      :model="ruleForm"
      :rules="rules"
      label-width="70px"
      class="demo-ruleForm"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="password">
        <el-input class="lf" style="width: 90px" v-model="ruleForm.password">
        </el-input>
        <el-button
          :disabled="codeLoading"
          class="code"
          type="primary"
          @click="getCode"
        >
          <span v-if="codeLoading">{{ num }}s后</span> 获取验证码</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue';
import { ElForm } from 'element-plus';

export default defineComponent({
  name: 'codeLogin',
  components: {},
  setup() {
    const codeLoading = ref<boolean>(false);
    const num = ref<number>(60);
    const ruleForm = reactive({
      phone: '',
      password: ''
    });
    const rules = {
      phone: [
        {
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        },
        {
          pattern: /^1[3|4|5|7|8]\d{9}$/,
          message: '请输入正确的手机号',
          trigger: 'blur'
        }
      ],
      password: [
        {
          required: true,
          message: '请输入验证码',
          trigger: 'blur'
        },
        {
          pattern: /^[0-9]{4,6}$/,
          message: '请输入正确的验证码',
          trigger: 'blur'
        }
      ]
    };

    const loginRef = ref<InstanceType<typeof ElForm>>();

    const actionSubmint = () => {
      loginRef.value?.validate((valid) => {
        if (valid) {
          console.log('暂时不做手机登录');
        }
      });
    };
    // 获取验证码
    const getCode = () => {
      let timer: number;
      if (!codeLoading.value) {
        num.value = 60;
        codeLoading.value = true;
        timer = setInterval(() => {
          num.value--;
          if (num.value == 0) {
            clearInterval(timer);
            codeLoading.value = false;
          }
        }, 1000);
      }
    };
    return {
      ruleForm,
      codeLoading,
      rules,
      num,
      loginRef,
      actionSubmint,
      getCode
    };
  }
});
</script>

<style lang="less">
.code {
  position: absolute;
  right: 0;
}
</style>
